package com.ruoyi;
import com.coupang.openapi.sdk.Hmac;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
//import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HmacProductCreation {

    private static final String HOST = "api-gateway.coupang.com";
    private static final int PORT = 443;
    private static final String SCHEMA = "https";
    //replace with your own accessKey
    private static final String ACCESS_KEY = "fe8a5ff1-28be-4a36-8694-577cc7960166";
    //replace with your own secretKey
    private static final String SECRET_KEY = "f05224e25ebb0c237564da5cce5be106926c7930";

    public void test() {
        //params
        String method = "POST";
        String vendorId = "A158000DM0";
        String path = "/v2/providers/openapi/apis/api/v5/vendors/" + vendorId + "/outboundShippingCenters";

        //replace with your own product registration json data
        // 注意：remoteInfos 中的金额字段需要特殊格式
        String strjson = "{\n" +
                "  \"vendorId\": \"A158000DM0\",\n" +
                "  \"userId\": \"zoejnson\",\n" +
                "  \"shippingPlaceName\": \"상품출고지 생성생성\",\n" +
                "  \"global\": false,\n" +
                "  \"usable\": true,\n" +
                "  \"placeAddresses\": [\n" +
                "    {\n" +
                "      \"addressType\": \"JIBUN\",\n" +
                "      \"countryCode\": \"KR\",\n" +
                "      \"companyContactNumber\": \"+82212345678\",\n" +
                "      \"phoneNumber2\": \"+821012345678\",\n" +
                "      \"returnZipCode\": \"10516\",\n" +
                "      \"returnAddress\": \"경기도 파주시 탄현면 월롱산로현면\",\n" +
                "      \"returnAddressDetail\": \"294-58\"\n" +
                "    }\n" +
                "  ]\n" +
                "}";

        CloseableHttpClient client = null;
        try {
            //create client
            client = HttpClients.createDefault();
            
            /********************************************************/
            //authorize, demonstrate how to generate hmac signature here
            // 注意：签名时使用的 path 必须与实际请求的 path 完全一致
            String authorization = Hmac.generate(method, path, SECRET_KEY, ACCESS_KEY);
            //print out the hmac key
            System.out.println(authorization);
            System.out.println("签名消息内容检查:");
            System.out.println("Method: " + method);
            System.out.println("Path: " + path);
            /********************************************************/

            //build uri
            URIBuilder uriBuilder = new URIBuilder()
                    .setScheme(SCHEMA)
                    .setHost(HOST)
                    .setPort(PORT)
                    .setPath(path);
            
            HttpPost requestPost = new HttpPost(uriBuilder.build().toString());

            StringEntity params = new StringEntity(strjson, "UTF-8");

            /********************************************************/
            // set headers, demonstarte how to use hmac signature here
            // 必需的请求头信息
            requestPost.addHeader("Authorization", authorization);
            requestPost.addHeader("X-Requested-By", vendorId);  // 重要：必须使用 vendorId，不是 ACCESS_KEY
            requestPost.addHeader("X-MARKET", "KR");  // KR=韩国市场，TW=台湾市场
            /********************************************************/
            requestPost.addHeader("Content-Type", "application/json");
            requestPost.setEntity(params);
            
            System.out.println("\n请求头信息:");
            System.out.println("X-Requested-By: " + vendorId);
            System.out.println("X-MARKET: KR");
            System.out.println("请求 URL: " + uriBuilder.build().toString());
            
            CloseableHttpResponse response = null;
            try {
                //execute post request
                response = client.execute(requestPost);
                //print result
                System.out.println("status code:" + response.getStatusLine().getStatusCode());
                System.out.println("status message:" + response.getStatusLine().getReasonPhrase());
                HttpEntity entity = response.getEntity();
                System.out.println("result:" + EntityUtils.toString(entity));
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (response != null) {
                    try {
                        response.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (client != null) {
                try {
                    client.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        HmacProductCreation hmacTest = new HmacProductCreation();
        hmacTest.test();
    }
}